#!/usr/bin/env python3
"""
Evergreen CLI configuration generator for DevContainers.

Generates evergreen_cli_config.env with URLs and SHA256 checksums for both ARM64 and AMD64.
"""

import os
import sys
import tempfile
from datetime import datetime

# Add script directory to path for importing local modules
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from s3_artifact_utils import calculate_sha256, download_file

# Default Evergreen CLI version
DEFAULT_EVERGREEN_VERSION = "4abdb95261a646cdd4b979e8717f261d830e6a0b"

# S3 bucket and prefix
BUCKET = "evg-bucket-evergreen"
PREFIX = "evergreen/clients"


def fetch_evergreen_cli_info(arch: str, version: str) -> dict:
    """Fetch Evergreen CLI info for a specific architecture."""
    print(f"\n🔍 Fetching {arch} Evergreen CLI...", file=sys.stderr)

    arch_path = f"linux_{arch}"
    url = f"https://{BUCKET}.s3.amazonaws.com/{PREFIX}/evergreen_{version}/{arch_path}/evergreen"
    print(f"URL: {url}", file=sys.stderr)

    # Download to temp location to calculate checksum
    with tempfile.NamedTemporaryFile(delete=False, suffix=".bin") as tmp:
        tmp_path = tmp.name

    try:
        download_file(url, tmp_path)
        sha256 = calculate_sha256(tmp_path)
        print(f"SHA256: {sha256}", file=sys.stderr)
    finally:
        os.unlink(tmp_path)

    return {
        "url": url,
        "sha256": sha256,
        "arch_path": arch_path,
        "version": version,
    }


def main():
    """Generate Evergreen CLI configuration file."""
    version = DEFAULT_EVERGREEN_VERSION
    print(f"Using version: {version}", file=sys.stderr)

    # Fetch both architectures
    arm64_info = fetch_evergreen_cli_info("arm64", version)
    amd64_info = fetch_evergreen_cli_info("amd64", version)

    # Determine output path
    script_dir = os.path.dirname(os.path.abspath(__file__))
    output_file = os.path.join(script_dir, "evergreen_cli_config.env")

    # Write config file
    with open(output_file, "w") as f:
        f.write("# Generated by evergreen_cli.py\n")
        f.write("# DO NOT EDIT MANUALLY - run: python3 evergreen_cli.py\n")
        f.write("#\n")
        f.write(f"# Generated: {datetime.now().isoformat()}\n")
        f.write(f"# Version: {version}\n")
        f.write("\n")
        f.write("# ARM64 Evergreen CLI\n")
        f.write(f'EVERGREEN_CLI_ARM64_URL="{arm64_info["url"]}"\n')
        f.write(f'EVERGREEN_CLI_ARM64_SHA256="{arm64_info["sha256"]}"\n')
        f.write(f'EVERGREEN_CLI_ARM64_ARCH="{arm64_info["arch_path"]}"\n')
        f.write(f'EVERGREEN_CLI_ARM64_VERSION="{arm64_info["version"]}"\n')
        f.write("\n")
        f.write("# AMD64 Evergreen CLI\n")
        f.write(f'EVERGREEN_CLI_AMD64_URL="{amd64_info["url"]}"\n')
        f.write(f'EVERGREEN_CLI_AMD64_SHA256="{amd64_info["sha256"]}"\n')
        f.write(f'EVERGREEN_CLI_AMD64_ARCH="{amd64_info["arch_path"]}"\n')
        f.write(f'EVERGREEN_CLI_AMD64_VERSION="{amd64_info["version"]}"\n')

    print(f"\n✅ Configuration written to: {output_file}", file=sys.stderr)
    print("\nContents:", file=sys.stderr)
    with open(output_file) as f:
        print(f.read(), file=sys.stderr)


if __name__ == "__main__":
    main()
